package client.backend.price;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;

/**
 * PricesThread constantly checks for new prices.
 * 
 */
public class PricesThread extends Thread {

	volatile boolean checking;
	
	private int port;
	private MulticastSocket socket;
	private InetAddress address;
	
	/**
	 * Constructor on a specified port.
	 * @param port	Port used for connection.
	 */
	public PricesThread(int port) {
		super("PricesThread");
		this.port = port;
	}
	
	/**
	 * Kills the thread.
	 */
	public void kill() {
		checking = false;
	}
	
	/**
	 * Starts the thread.
	 */
	public void run() {
		checking = true;
		listen();
	}
	
	/**
	 * Private method to open connection.
	 */
	private void connect() {
		try {
			socket = new MulticastSocket(port);
			address = InetAddress.getByName("230.0.0.1");
			socket.joinGroup(address);
			socket.setSoTimeout(1000);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Closes the connection.
	 */
	private void close() {
		try {
			socket.leaveGroup(address);
		} catch (IOException e) {
			e.printStackTrace();
		}
        socket.close();
	}

	/**
	 * Checks for incoming packages.
	 */
	private void listen() {
		connect();
		
		while (checking) {
			DatagramPacket packet;

			byte[] buf = new byte[256];
			packet = new DatagramPacket(buf, buf.length);
			try {
				socket.receive(packet);
				String received = new String(packet.getData(), 0, packet.getLength());
				PriceController.getInstance().updatePrices(received);
			} catch (SocketException e) {
				// timeout -> ignore
			} catch (IOException e) {
				// ignore
			}	
		}
		
		close();
	}
}
